package cn.wolfcode.business.service.impl;

import cn.wolfcode.business.domain.BusBpmnInfo;
import cn.wolfcode.business.domain.BusCarPackageAudit;
import cn.wolfcode.business.domain.BusServiceItem;
import cn.wolfcode.business.domain.vo.AuditInfoVO;
import cn.wolfcode.business.domain.vo.AuditVo;
import cn.wolfcode.business.mapper.BusServiceItemMapper;
import cn.wolfcode.business.service.BusBpmnInfoService;
import cn.wolfcode.business.service.IBusCarPackageAuditService;
import cn.wolfcode.business.service.IBusServiceItemService;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.exception.ServiceException;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.service.ISysConfigService;
import cn.wolfcode.system.service.ISysUserService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务项Service业务层处理
 * 
 * @author wolfcode
 * @date 2025-09-19
 */
@Service
public class BusServiceItemServiceImpl implements IBusServiceItemService 
{
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IBusCarPackageAuditService busCarPackageAuditService;
    @Autowired
    private BusBpmnInfoService busBpmnInfoService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id)
    {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem)
    {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItem busServiceItem)
    {
        //参数合理化校验
        if(busServiceItem==null){
            throw new ServiceException("参数不能为空");
        }
        if(busServiceItem.getName()==null||
        busServiceItem.getOriginalPrice()==null||
        busServiceItem.getDiscountPrice()==null||
        busServiceItem.getCarPackage()==null||
        busServiceItem.getServiceCatalog()==null||
        busServiceItem.getInfo()==null){
            throw new ServiceException("参数不能为空");
        }
        //价格合理化验证
        //原价大于等于0 折扣价大于等于0 小于等于原价
        //BigDecimal 的运算不能使用运算符
        //xx.compareTo(yy) xx大于yy 返回1  等于返回0  小于返回-1
        if (busServiceItem.getOriginalPrice().compareTo(BigDecimal.ZERO)<0){
            throw new ServiceException("原价不能小于0");
        }

        if (busServiceItem.getDiscountPrice().compareTo(BigDecimal.ZERO)<0){
            throw new ServiceException("折扣价不能小于0");
        }
        if (busServiceItem.getDiscountPrice().compareTo(busServiceItem.getOriginalPrice())>0){
            throw new ServiceException("折扣价不能大于原价");
        }
        //判断插入的数据是否为套餐
        if(BusServiceItem.CARPACKAGE_NO.equals(busServiceItem.getCarPackage())){
            //不是套餐，初始化状态为4
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }else {
            //是套餐，初始化状态为0
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        //提高代码安全性设置，将默认的上下架设置为下架状态
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
        busServiceItem.setCreateTime(DateUtils.getNowDate());
        return busServiceItemMapper.insertBusServiceItem(busServiceItem);
    }

    /**
     * 修改服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItem busServiceItem)
    {
        //参数合理化校验
        if(busServiceItem==null){
            throw new ServiceException("参数不能为空");
        }
        if(busServiceItem.getName()==null||
                busServiceItem.getOriginalPrice()==null||
                busServiceItem.getDiscountPrice()==null||
                busServiceItem.getCarPackage()==null||
                busServiceItem.getServiceCatalog()==null||
                busServiceItem.getInfo()==null){
            throw new ServiceException("参数不能为空");
        }
        //价格合理化验证
        //原价大于等于0 折扣价大于等于0 小于等于原价
        //BigDecimal 的运算不能使用运算符
            //xx.compareTo(yy) xx大于yy 返回1  等于返回0  小于返回-1
            if (busServiceItem.getOriginalPrice().compareTo(BigDecimal.ZERO)<0){
            throw new ServiceException("原价不能小于0");
        }

        if (busServiceItem.getDiscountPrice().compareTo(BigDecimal.ZERO)<0){
            throw new ServiceException("折扣价不能小于0");
        }
        if (busServiceItem.getDiscountPrice().compareTo(busServiceItem.getOriginalPrice())>0){
            throw new ServiceException("折扣价不能大于原价");
        }
        //验证是否套餐禁止修改
        //查询原始对象
        BusServiceItem oldObj = this.selectBusServiceItemById(busServiceItem.getId());
        if (oldObj == null || oldObj.getCarPackage()==null||oldObj.getAuditStatus()==null){
            throw new ServiceException("禁止修改套餐");
        }
        //验证是否上架禁止修改
        if (!oldObj.getCarPackage().equals(busServiceItem.getCarPackage())){
            throw new ServiceException("是否套餐禁止修改");
        }
        //上架状态禁止修改
        if (!oldObj.getSaleStatus().equals(busServiceItem.getSaleStatus())
        ||busServiceItem.getSaleStatus().equals(BusServiceItem.SALESTATUS_ON)){
            throw new ServiceException("上架状态禁止修改");
        }
        //验证审批状态
        if (!oldObj.getAuditStatus().equals(busServiceItem.getAuditStatus())){
            throw new ServiceException("审批状态禁止修改");
        }
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())||
        BusServiceItem.AUDITSTATUS_AUDITING.equals(busServiceItem.getAuditStatus())){
            throw new ServiceException("套餐审批中禁止修改");
        }
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())&&
                BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())||
                BusServiceItem.AUDITSTATUS_REPLY.equals(busServiceItem.getAuditStatus())) {
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
     }
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     * 
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids)
    {
        return busServiceItemMapper.deleteBusServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     * 
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id)
    {
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    @Override
    public int saleOnHandle(Long id) {
        if (id==null){
            throw new ServiceException("服务项id不能为空");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem==null){
            throw new ServiceException("服务项不存在");
        }
        if (BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())){
            throw new ServiceException("服务项已上架,请勿重复操作");
        }
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())
        && !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())){
            throw new ServiceException("服务项未审核通过,请审核通过后再上架");
        }
        return busServiceItemMapper.changeSaleStatus(id, BusServiceItem.SALESTATUS_ON);
    }

    @Override
    public int saleDownHandle(Long id) {
        if (id==null){
            throw new ServiceException("非法参数");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem==null){
            throw new ServiceException("服务项不存在");
        }
        if (BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())){
            throw new ServiceException("服务项已下架,请勿重复操作");
        }
        return busServiceItemMapper.changeSaleStatus(id, BusServiceItem.SALESTATUS_OFF);
    }

    @Override
    public AuditInfoVO createAuditInfo(Long id) {
        if (id==null){
            throw new ServiceException("非法参数");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem==null){
            throw new ServiceException("非法参数");
        }
        AuditInfoVO vo = new AuditInfoVO();
        vo.setServiceItem(busServiceItem);
        List<SysUser> shopOwners = sysUserService.selectUser("shopOwner");
        vo.setShopOwners(shopOwners);
        String discountPriceLimit = sysConfigService.selectConfigByKey("discountPriceLimit");
        vo.setDiscountPrice(new BigDecimal(discountPriceLimit));
        if (busServiceItem.getDiscountPrice().compareTo(vo.getDiscountPrice())>=0){
            List<SysUser> finance = sysUserService.selectUser("finance");
            vo.setFinances(finance);
        }
        return vo;
    }

    @Override
    @Transactional
    public int startAudit(AuditVo vo) {
        if(vo==null){
            throw new ServiceException("非法参数");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(vo.getServiceItemId());
        if (busServiceItem==null){
            throw new ServiceException("非法参数");
        }
        if (!BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())){
            throw new ServiceException("只有套餐才能发起审批");
        }
        if(!BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())){
            throw new ServiceException("只有下架状态才能发起审批");
        }
        if(!BusServiceItem.AUDITSTATUS_INIT.equals(busServiceItem.getAuditStatus())){
            throw new ServiceException("只有初始化状态才能发起审批");
        }
        BusCarPackageAudit busCarPackageAudit = new BusCarPackageAudit();
        busCarPackageAudit.setServiceItemId(busServiceItem.getId());
        busCarPackageAudit.setServiceItemName(busServiceItem.getName());
        busCarPackageAudit.setServiceItemInfo(busServiceItem.getInfo());
        busCarPackageAudit.setServiceItemPrice(busServiceItem.getDiscountPrice());
        busCarPackageAudit.setCreatorId(SecurityUtils.getUserId().toString());
        busCarPackageAudit.setInfo(vo.getInfo());
        busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_IN_PROGRESS);
        busCarPackageAuditService.insert(busCarPackageAudit);

        BusBpmnInfo bpmnInfo = busBpmnInfoService.selectType(BusCarPackageAudit.FLOW_AUDIT_TYPE);
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        String businessKey = busCarPackageAudit.getId().toString();
        Map<String, Object> variables = new HashMap<>();
        variables.put("shopOwnerId",vo.getShopOwnerId());
        if (vo.getFinanceId()!=null){
            variables.put("financeId",vo.getFinanceId());
        }
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                processDefinitionKey, businessKey, variables);
        busCarPackageAudit.setInstanceId(processInstance.getProcessInstanceId());
        busCarPackageAuditService.update(busCarPackageAudit);
        return busServiceItemMapper.updateStatus(vo.getServiceItemId(),BusServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public int updateStatus(Long serviceItemId, Integer auditstatusInit) {
        return busServiceItemMapper.updateStatus(serviceItemId,auditstatusInit);
    }
}
